package com.hard;

import java.util.*;

public class Solution51 {
    char[][] chars;
    List<List<String>> res = new ArrayList<>();
    public List<List<String>> solveNQueens(int n) {
        chars = new char[n][n];
        for (char[] c : chars) {
            Arrays.fill(c, '.');
        }
        backtracking(n, 0);
        return res;
    }

    public void backtracking(int n, int row) {
        if (row == n) {
            res.add(arrayToList(chars));
            return;
        }
        for (int i = 0; i < n; i++) {
            if (check(row, i, n)) {
                chars[row][i] = 'Q';
                backtracking(n, row + 1);
                chars[row][i] = '.';
            }
        }
    }

    public List<String> arrayToList(char[][] chars) {
        List<String> tmp = new ArrayList<>();
        for (char[] c : chars) {
            tmp.add(String.copyValueOf(c));
        }
        return tmp;
    }

    public boolean check(int row, int col, int n) {
        for (int i = 0; i < row; i++) {
            if (chars[i][col] == 'Q') return false;
        }
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (chars[i][j] == 'Q') return false;
        }
        for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
            if (chars[i][j] == 'Q') return false;
        }
        return true;
    }
}
